<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input style="width: 360px;" v-model="find_data.find" placeholder="客户关键字搜索" clearable
                        prefix-icon="Search" />

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <el-button @click="out_btn" type="warning" icon="Share">导出</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'receiveMsg'" #="{ row, column, $index }">
                                <span>{{ row.receiveMsg ? '通知' : '不通知' }}</span>

                            </template>

                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                    :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import CircularJSON from 'circular-json'
import { getBillList, billexport, adupPrivateSet, getPrivateSetList } from '@/api/billing_settings.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx';
onMounted(async () => {
    let billing_settings = JSON.parse(localStorage.getItem('billing_settings'))
    if (billing_settings) {
        find_data.find = billing_settings.find

    }
    getPrivateSetList({
        find: '账单列表',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })


    await list_api()
})

//#region 表格数据处理
const table_data_list = reactive([
    { label: '客户姓名', field: 'userName', width: '', off: true },
    { label: '账单编号', field: 'code', width: '', off: true },
    { label: '账单金额', field: 'price', width: '', off: true },
    { label: '账期', field: 'billDate', width: '', off: true },
    { label: '最后还款日', field: 'endTime', width: '', off: true },
    { label: '滞纳金', field: 'outPrice', width: '', off: true },
    { label: '是否消息通知', field: 'receiveMsg', width: '', off: true },
    { label: '添加时间', field: 'addTime', width: 165, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '账单列表',
        tbNum: "billing_settings",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    find: ''
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    getBillList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion



//#region 搜索
const search_btn = () => {
    localStorage.setItem('billing_settings', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion

//#region 订单导出
const out_btn = () => {
    // if (table_list.value.length != 1) {
    //     return ElMessage({
    //         message: '请选择数据一条数据！',
    //         type: 'warning',
    //     })
    // }
    // let response = await omsorderexport({ id: table_list.value[0].id })
    // let url = window.URL.createObjectURL(new Blob([response.data])); // 创建包含响应数据的 Blob 对象
    // const link = document.createElement('a'); // 创建一个隐藏的链接元素
    // link.href = url;
    // link.setAttribute('download', '原始订单列表.xlsx'); // 设置文件名
    // document.body.appendChild(link); // 将链接元素添加到文档中
    // link.click(); // 模拟点击链接进行下载
    // link.remove(); // 下载完成后移除链接元素


    billexport(find_data).then(res => {
        console.log(res)
        if (res.code == 1) {
            const data = [
                ['客户姓名', '账号编号', '账单金额', '账期', '最后还款日期', '滞纳金', '是否消息通知', '添加时间',],
            ];
            for (let i = 0; i < res.data.length; i++) {
                let ps = {
                    userName: res.data[i].userName,
                    code: res.data[i].code,
                    price: res.data[i].price,
                    billDate: res.data[i].billDate,
                    endTime: res.data[i].endTime,
                    outPrice: res.data[i].outPrice,
                    receiveMsg: res.data[i].receiveMsg ? '通知' : '不通知',
                    addTime: res.data[i].addTime,

                }
                data.push(Object.values(ps))
            }
            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '客车帮服务后台系统管理-账单列表.xlsx');
            list_api()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })

}
//#endregion
</script>

<style scoped lang='scss'>
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
